package com.sweet.image;

import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 压缩图片
 *
 * @author limi
 * @date 2023/2/14 18:23
 */
public class ResizeImage {
    public static void main(String[] args) {
        File file = new File("d:/a.png");
        resizeImage(file, new File("d:/d.png"), 500);
    }

    /**
     * 压缩指定图片
     *
     * @param fromImage   来源图片
     * @param targetImage 目标图片
     * @param maxWidth    最大宽度
     */
    public static void resizeImage(File fromImage, File targetImage, int maxWidth) {
        if (fromImage == null || !fromImage.exists() || !fromImage.isFile()) {
            System.out.println("路径无效：fromFile=" + fromImage.getAbsolutePath() + ",是否存在:" + fromImage.exists() + "," +
                    "是否目录：" + fromImage.isDirectory());
            System.out.println("路径无效：targetFile=" + targetImage.getAbsolutePath() + ",是否存在:" + targetImage.exists() +
                    "," +
                    "是否目录：" + targetImage.isDirectory());
            return;
        }

        //System.out.println("压缩图片(" + maxWidth + ")：" + fromImage.getAbsolutePath());
        //System.out.println("压缩前大小：" + (fromImage.length() / 1024) + "kb");

        //获取文件后缀
        String suffix = fromImage.getName().substring(fromImage.getName().lastIndexOf(".") + 1);

        try {
            //读取图片
            BufferedImage bi = ImageIO.read(fromImage);
            if (bi.getWidth() <= maxWidth) {
                System.out.println("无需压缩,拷贝到：" + targetImage.getAbsolutePath());
                FileUtils.copyFile(fromImage, targetImage);
                return;
            }

            //计算比例
            double ratio = (new Integer(maxWidth)).doubleValue() / bi.getWidth();
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            Image image = op.filter(bi, null);

            //另存为
            ImageIO.write((BufferedImage) image, suffix, targetImage);

            //System.out.println("压缩后大小：" + (targetImage.length() / 1024) + "kb");
            System.out.println("压缩前后：" + (fromImage.length() / 1024) + "kb -> " + (targetImage.length() / 1024) + "kb");
        } catch (Exception e) {
            //压缩异常，原样拷贝
            try {
                FileUtils.copyFile(fromImage, targetImage);
            } catch (Exception e2) {
                System.out.println("拷贝异常:" + fromImage.getAbsolutePath());
                e.printStackTrace();
            }
            System.out.println("压缩异常：" + fromImage.getAbsolutePath());
            e.printStackTrace();
        }
    }

    /**
     * 压缩指定图片
     *
     * @param file     文件数据
     * @param maxWidth 最大宽度
     */
    public static void resizeImage(File file, int maxWidth) {
        if (file == null || !file.exists() || !file.isFile()) {
            System.out.println("路径无效：file=" + file.getAbsolutePath() + ",是否存在:" + file.exists() + "," +
                    "是否目录：" + file.isDirectory());
            return;
        }

        //获取文件后缀
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);

        try {
            //读取图片
            BufferedImage bi = ImageIO.read(file);
            if (bi.getWidth() <= maxWidth) {
                //System.out.println("无需压缩：" + file.getAbsolutePath());
                return;
            }

            System.out.println("压缩图片：" + file.getAbsolutePath());
            System.out.println("压缩最大宽度：" + maxWidth);
            System.out.println("压缩前大小：" + (file.length() / 1024) + "kb");

            //计算比例
            double ratio = (new Integer(maxWidth)).doubleValue() / bi.getWidth();
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            Image image = op.filter(bi, null);

            //另存为
            ImageIO.write((BufferedImage) image, suffix, file);

            System.out.println("压缩后大小：" + (file.length() / 1024) + "kb");
        } catch (Exception e) {
            System.out.println("压缩异常：" + file.getAbsolutePath());
            e.printStackTrace();
        }
    }
}